'use client'
import React, { useState } from 'react';
import { ArrowLeft, Calendar, User, Tag, Clock, Share2, Eye, Heart } from 'lucide-react';
import parse from 'html-react-parser';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Separator } from './ui/separator';
import type { BlogPost as BlogPostType } from './BlogCard';
import CommentForm from './CommentForm';
import CommentList, { CommentListRef } from './CommentList';
import { Comment } from '../types/comment';
import { ImgProcess, shareContent } from '../utils/common';
import { likeArticle, unlikeArticle, checkIsLiked } from '../services/likeService';

interface BlogPostProps {
  post: BlogPostType;
  onBack: () => void;
}

export default function BlogPost({ post, onBack }: BlogPostProps) {
  const commentListRef = React.useRef<CommentListRef>(null);
  const [likeCount, setLikeCount] = useState<number>(post.likeCount || 0);
  const [isLiked, setIsLiked] = useState<boolean>(false);

  const handleLike = async () => {
    try {
      if (isLiked) {
        await unlikeArticle(post.id);
        setLikeCount(prev => Math.max(0, prev - 1));
      } else {
        await likeArticle(post.id);
        setLikeCount(prev => prev + 1);
      }
      setIsLiked(!isLiked);
    } catch (error) {
      console.error('点赞操作失败:', error);
      alert('操作失败，请稍后重试');
    }
  };

  // 组件加载时检查用户是否已点赞
  React.useEffect(() => {
    const checkLikedStatus = async () => {
      try {
        const result = await checkIsLiked(post.id);
        setIsLiked(result.isLiked);
      } catch (error) {
        console.error('检查点赞状态失败:', error);
        // 保持默认状态（未点赞）
      }
    };

    checkLikedStatus();
  }, [post.id]);


  return (
    <article className="max-w-4xl mx-auto">
      <Button 
        variant="ghost" 
        onClick={onBack}
        className="mb-6"
      >
        <ArrowLeft className="w-4 h-4 mr-2" />
        返回文章列表
      </Button>

      <div className="bg-white rounded-lg shadow-sm overflow-hidden">
        <div className="aspect-[21/9] overflow-hidden">
          <img
            src={ImgProcess(post.image)}
            alt={post.title}
            className="w-full h-full object-cover"
          />
        </div>

        <div className="p-8 md:p-12">
          <div className="flex items-center gap-3 mb-6">
            <Badge>{post.category || '未分类'}</Badge>
            <div className="flex items-center gap-1 text-sm text-gray-500">
              <Clock className="w-4 h-4" />
              {post.readTime}
            </div>
          </div>

          <h1 className="text-gray-900 mb-6">
            {post.title}
          </h1>

          <div className="flex items-center justify-between mb-8 pb-8 border-b border-gray-200">
            <div className="flex items-center gap-6 text-gray-600">
              <div className="flex items-center gap-2">
                <User className="w-4 h-4" />
                {post.author}
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4" />
                {post.date}
              </div>
              <div className="flex items-center gap-2">
                <Eye className="w-4 h-4" />
                {post.viewCount || 0}
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Button 
                variant="outline" 
                size="sm"
                onClick={handleLike}
                className="flex items-center gap-1"
              >
                <Heart 
                  className={`w-4 h-4 ${isLiked ? 'fill-red-500 text-red-500' : ''}`} 
                />
                {likeCount}
              </Button>
              <Button 
                variant="outline" 
                size="sm"
                onClick={() => shareContent(undefined, post.title, post.id)}
              >
                <Share2 className="w-4 h-4 mr-2" />
                分享
              </Button>
            </div>
          </div>

         <div className="prose prose-lg max-w-none mb-8">
            {/* 渲染富文本内容 */}
            {post.content ? parse(post.content) : parse(post.excerpt)}
          </div> 

          <Separator className="my-8" />

          <div className="flex flex-wrap gap-2">
            <span className="flex items-center gap-1 text-gray-600">
              <Tag className="w-4 h-4" />
              标签:
            </span>
            {post.tags.map((tag) => (
              <Badge key={tag} variant="secondary" className="cursor-pointer">
                {tag}
              </Badge>
            ))}
          </div>
        </div>
      </div>
      
      {/* 评论区域 */}
      <div className="mt-12">
        <CommentForm 
          articleId={String(post.id || '0')} 
          onCommentCreated={(newComment: Comment) => {
            // 通过ref将新评论添加到评论列表开头
            if (commentListRef.current) {
              commentListRef.current.addComment(newComment);
            }
          }} 
        />
        
        <CommentList 
          articleId={String(post.id || '0')} 
          ref={commentListRef}
        />
      </div>
    </article>
  );
}